//
//  RigisterViewController.m
//  YaDiuDiu
//
//  Created by 欧洪飞 on 2017/8/19.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "RigisterViewController.h"

#import "RigisterView.h"
#import "RigisterServerceViewController.h"

#import <AVFoundation/AVFoundation.h>
//#import "QRCodeGenerateVC.h"
#import "SGQRCodeScanningVC.h"
@interface RigisterViewController ()<UITextFieldDelegate,SGQRCodeScanningVCDelegate>{
    NSInteger count;
    RigisterView *rigView;
}
@property (weak, nonatomic) IBOutlet UITextField *textNum;
@property (weak, nonatomic) IBOutlet UITextField *textCode;
@property (weak, nonatomic) IBOutlet UITextField *textPwdF;
@property (weak, nonatomic) IBOutlet UITextField *textPwdS;
@property (weak, nonatomic) IBOutlet UITextField *textYqm;
@property (weak, nonatomic) IBOutlet UILabel *labYQM;

@property (weak, nonatomic) IBOutlet UIView *view1;
@property (weak, nonatomic) IBOutlet UIView *view2;
@property (weak, nonatomic) IBOutlet UIView *view3;
@property (weak, nonatomic) IBOutlet UIView *view4;
@property (weak, nonatomic) IBOutlet UIView *view5;

@property (weak, nonatomic) IBOutlet UIButton *btnCode;
@property (weak, nonatomic) IBOutlet UIButton *btnAgree;

@property (nonatomic,copy) NSString *content;

@end

@implementation RigisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _view1.layer.borderWidth = 1.0;
    _view1.layer.borderColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1.0].CGColor;
    
    _view2.layer.borderWidth = 1.0;
    _view2.layer.borderColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1.0].CGColor;
    
    _view3.layer.borderWidth = 1.0;
    _view3.layer.borderColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1.0].CGColor;
    
    _view4.layer.borderWidth = 1.0;
    _view4.layer.borderColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1.0].CGColor;
    
    _view5.layer.borderWidth = 1.0;
    _view5.layer.borderColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1.0].CGColor;
    
    _textYqm.delegate = self;
    
    [self loadNav];
    
    _labYQM.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click)];
    [_labYQM addGestureRecognizer:tap];
    
}

- (void)click{
    // 1、 获取摄像设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device) {
        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (status == AVAuthorizationStatusNotDetermined) {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        SGQRCodeScanningVC *vc = [[SGQRCodeScanningVC alloc] init];
                        [self.navigationController pushViewController:vc animated:YES];
                    });
                    // 用户第一次同意了访问相机权限
                    NSLog(@"用户第一次同意了访问相机权限 - - %@", [NSThread currentThread]);
                    
                } else {
                    // 用户第一次拒绝了访问相机权限
                    NSLog(@"用户第一次拒绝了访问相机权限 - - %@", [NSThread currentThread]);
                }
            }];
        } else if (status == AVAuthorizationStatusAuthorized) { // 用户允许当前应用访问相机
            SGQRCodeScanningVC *vc = [[SGQRCodeScanningVC alloc] init];
            vc.delegate = self;
            [self.navigationController pushViewController:vc animated:YES];
        } else if (status == AVAuthorizationStatusDenied) { // 用户拒绝当前应用访问相机
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请去-> [设置 - 隐私 - 相机 - SGQRCodeExample] 打开访问开关" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            
            [alertC addAction:alertA];
            [self presentViewController:alertC animated:YES completion:nil];
            
        } else if (status == AVAuthorizationStatusRestricted) {
            NSLog(@"因为系统原因, 无法访问相册");
        }
    } else {
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"未检测到您的摄像头" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertC addAction:alertA];
        [self presentViewController:alertC animated:YES completion:nil];
    }
}

#pragma - mark delegate
-(void)sendText:(NSString *)str{
    _labYQM.text = str;
    _labYQM.textColor = [UIColor blackColor];
}

- (void)loadNav{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 64)];
    view.backgroundColor = [UIColor whiteColor];
    view.userInteractionEnabled = YES;
    [self.view addSubview:view];
    
    UILabel *line = [[UILabel alloc] init];
    line.backgroundColor = [UIColor lightGrayColor];
    [view addSubview:line];
    [line makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(0);
        make.right.equalTo(0);
        make.bottom.equalTo(view.bottom);
        make.height.equalTo(0.5);
    }];
    
    UILabel *lab = [[UILabel alloc] init];
    lab.text = @"注册";
    lab.textColor = [UIColor blackColor];
    lab.font = [UIFont systemFontOfSize:18.0];
    [view addSubview:lab];
    [lab makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(view.centerX);
        make.top.equalTo(34);
    }];
    
    //返回按钮
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"箭头"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"箭头"] forState:UIControlStateHighlighted];
    [btn addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    [btn makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(lab.centerY);
        make.left.equalTo(10);
        make.width.equalTo(30);
        make.height.equalTo(30);
    }];
    
}

- (void)clickBack{
//    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}
//获取验证码
- (IBAction)clickCode:(id)sender {
    if (_textNum.text.length == 0) {
        
        [LICGToast showWithText:@"手机号格式有误"];
        return;
    }else if ([self validateMobile:_textNum.text] == 0){
        [LICGToast showWithText:@"手机号格式不对"];
        return;
    }
    
    else{
        [self performSelector:@selector(countClick) withObject:nil];
        _btnCode.enabled = NO;
        NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
        [parmas setObject:_textNum.text forKey:@"mobile"];
        [parmas setObject:@"1" forKey:@"k"];
        NSLog(@"parmas:%@",parmas);
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        NSString *url = [NSString stringWithFormat:@"%@/App/Userlogin/CallSms",urlHead];
        [manager POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
            NSLog(@"res:%@",responseObject);
            NSString *str = [responseObject objectForKey:@"status"];
            if ([str integerValue] == 200) {
                
                [LICGToast showWithText:@"短信发送成功"];
            }else{
                
                [LICGToast showWithText:[responseObject objectForKey:@"msg"]];
            }
            
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
}
//倒计时方法
-(void)countClick
{
    
    count = 119;
    [_btnCode setTitle:@"119秒后重新获取" forState:UIControlStateNormal];
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
}

- (void)timerFired:(NSTimer *)time{
    if (count !=1) {
        count -=1;
        NSString *str = [NSString stringWithFormat:@"%li",count];
        NSString *str2 = @"秒后重新获取";
        NSString *title = [NSString stringWithFormat:@"%@%@",str,str2];
        [_btnCode setTitle:title forState:UIControlStateNormal];
    }else{
        [time invalidate];//关闭定时器
        _btnCode.enabled = YES;
        [_btnCode setTitle:@"获取验证码" forState:UIControlStateNormal];
    }
}
//同意
- (IBAction)clickAgree:(UIButton *)sender {
    if (sender.tag == 10) {
        [sender setImage:[UIImage imageNamed:@"勾-(1)"] forState:UIControlStateNormal];
        sender.tag = 20;
    }else{
        [sender setImage:[UIImage imageNamed:@"矩形-7"] forState:UIControlStateNormal];
        sender.tag = 10;
    }
}
//注册协议
- (IBAction)clickService:(id)sender {
    RigisterServerceViewController *server = [[RigisterServerceViewController alloc] init];
    [self.navigationController pushViewController:server animated:YES];
}
//注册
- (IBAction)clickRigister:(id)sender {
    if (_textNum.text.length == 0) {
        
        [LICGToast showWithText:@"手机号码不能为空"];
    }else if ([self validateMobile:_textNum.text] == 0){
        [LICGToast showWithText:@"手机号码格式不正确"];
    }
    else if (_textCode.text.length == 0){
        
        [LICGToast showWithText:@"验证码不能为空"];
    }else if ([self judgePassWordLegal:_textPwdF.text] == 0){//
        
        [LICGToast showWithText:@"密码格式有误"];
    }else if (![_textPwdF.text isEqualToString:_textPwdS.text]){
        
        [LICGToast showWithText:@"两次密码不一致"];
    }else if (self.btnAgree.tag == 10){
        
        [LICGToast showWithText:@"请阅读并同意丫丢丢服务协议"];
    }else{
        [SVProgressHUD show];
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
        NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
        [parmas setObject:_textNum.text forKey:@"mobilephone"];
        [parmas setObject:_textPwdS.text forKey:@"password"];
        if ([_labYQM.text isEqualToString:@"请扫描邀请码（选填）"]) {
            
        }else{
            [parmas setObject:_labYQM.text forKey:@"invatationcode"];
        }
        
        [parmas setObject:_textCode.text forKey:@"smscode"];
        NSLog(@"parmas:%@",parmas);
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        NSString *url = [NSString stringWithFormat:@"%@/App/Userlogin/userRegister",urlHead];
        [manager POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
            NSLog(@"res:%@",responseObject);
            NSString *status = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"status"] integerValue]];
            if ([status integerValue] == 200) {
                [LICGToast showWithText:@"注册成功"];
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [LICGToast showWithText:[responseObject objectForKey:@"msg"]];
            }
            
            [SVProgressHUD dismiss];
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            NSLog(@"error:%@",error);
            [SVProgressHUD dismiss];
        }];
    }
    
}

//登录
- (IBAction)clickLogin:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
